package com.msi.shortwave;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.msi.shortwave.home.doupdate.Progress;

import android.support.v4.app.Fragment;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class home extends Fragment {
	Boolean online;
	View v;
	public static final String PREFS_NAME = "swprefs";
	public boolean isOnline() {
		
		if (AppStatus.getInstance(getActivity()).isOnline((getActivity()))){
			return true;
		}else{
			//blackberry below
			//return true;
			//android below
			return false;
		}
	}
	
	private void mLockScreenRotation()
	{
	  // Stop the screen orientation changing during an event
	    switch (this.getResources().getConfiguration().orientation)
	    {
	  case Configuration.ORIENTATION_PORTRAIT:
	    getActivity().setRequestedOrientation(
	ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	    break;
	  case Configuration.ORIENTATION_LANDSCAPE:
		  getActivity().setRequestedOrientation(
	ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
	    break;
	    }
	}
	
	   @Override
	   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
	      // Inflate the layout for this fragment
		   v = inflater.inflate(R.layout.home, container, false);
		   
		   Button update = (Button) v.findViewById(R.id.update);
		   final SharedPreferences settings = getActivity().getSharedPreferences(PREFS_NAME, 0);
		   
		   if (settings.getString("whatsnew402", "Never").compareTo("Never") == 0){
			   
			   new AlertDialog.Builder(getActivity())
			    .setTitle("Whats New...")
			    .setIcon(android.R.drawable.ic_menu_info_details)
			    .setMessage("* Log your shortwave listening. Click the icon next to the map on each search result to open the log station screen to add comments, your location and SINPO \n*"+
			    		" Make recordings of stations you receive. To do this click the microphone button from the log station screen. \n* Recordings and logs can be shared via Android share options"+
			    		"\n* New Chinese translation \n* Improved filtering of EiBi listings to remove out of date information. \n* Minor bug fixes.")
			    .setNegativeButton("Close", new DialogInterface.OnClickListener() {
			      public void onClick(DialogInterface dialog, int whichButton) {
			          //
			      }
			    }).show();
			      SharedPreferences.Editor editor = settings.edit();
			      editor.putString("whatsnew401", "seen");
			      editor.commit();
		   }
		
		   if (settings.getString("lastupdatenewt11", "Never").compareTo("Never") == 0){
  			 
  			 getActivity().deleteDatabase("shortwave");
  			 new doupdate().execute("");
  	        }else{
  	            String lastupdate  = settings.getString("lastupdatenewt11", "Never");
  	            TextView updatetv = (TextView) v.findViewById(R.id.lastupdate);
  	            updatetv.setText(getString(R.string.whenupdated) + lastupdate);
  	            
  	        }
		   
	    	update.setOnClickListener(new View.OnClickListener() {
	    	public void onClick(View v) {
	    		
	    		 new doupdate().execute("");
	    		
	        	

	    	}});
		   
	      return v;
	      
	      
	   }
	   
	   public home() {

	   }
	   
	   public class doupdate extends AsyncTask<String, Integer, String> {
	    	ProgressDialog loading;
	    	private Progress progress;

	        protected doupdate() {
	            this.progress = new Progress(this);
	        }

	    	@Override
	    	
	    	
	    	protected String doInBackground(String... params) {
	       
	            if (isOnline()==true){
	            	
	            online = true;
	    		main.updateschedule(progress, getActivity());
	            }else{
	            online = false;
	            }
	    		return null;
	    	}

	    	/* (non-Javadoc)
	    	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
	    	 */
	    	@Override
	    	protected void onPostExecute(String result) {
	    		
	    		if (online){
	    			
	    		
	    	    SimpleDateFormat f = new SimpleDateFormat("d MMMM y");
	    		String lastupdate = f.format(new Date());
	    		 SharedPreferences settings = getActivity().getSharedPreferences(PREFS_NAME,0);
			      SharedPreferences.Editor editor = settings.edit();
			      editor.putString("lastupdatenewt11", lastupdate.toUpperCase());

			      editor.commit();
	    		 TextView update = (TextView) v.findViewById(R.id.lastupdate);
	             update.setText(getString(R.string.whenupdated) + lastupdate);
	    		//set last updated
	             
	            while (loading.isShowing() == true){
	            	loading.dismiss();
	           }
	    		
	    		}else{
	    			  while (loading.isShowing() == true){
	    	            	loading.dismiss();
	    	            }
	    		

	    			Toast.makeText(getActivity(), R.string.nodata ,  Toast.LENGTH_SHORT).show();
	    		
	    		}
	    		getActivity().setRequestedOrientation(
	    				ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
	  			
	    	}

	    	/* (non-Javadoc)
	    	 * @see android.os.AsyncTask#onPreExecute()
	    	 */
	    	@Override
	    	protected void onPreExecute() {
	    	// Things to be done before execution of long running operation. For example showing ProgessDialog
	    		 mLockScreenRotation();
	    	 loading = ProgressDialog.show(getActivity(),getString(R.string.startdownload), getString(R.string.downloadtext), true);
	    	}

	    	/* (non-Javadoc)
	    	 * @see android.os.AsyncTask#onProgressUpdate(Progress[])
	    	 */
	    	@Override
	    	protected void onProgressUpdate(Integer... values) {
	          // Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
	    		//loading.dismiss();
	    		//loading = ProgressDialog.show(home.this,", "Downloading and organising shortwave schedules, this could take several minutes", true);
	    		loading.setTitle(getString(R.string.pleasewait) + String.valueOf(values[0]) + getString(R.string.completed));
	    	}
	    	
	    	 public class Progress {
	    	        private doupdate task;

	    	        public Progress(doupdate task) {
	    	            this.task = task;
	    	        }

	    	        public void publish(int val) {
	    	            task.publishProgress(val);
	    	        }
	    	    }
	    }
	        
	}